package com.transcargo.request;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.PrintWriter;
import java.io.IOException;

import com.transcargo.action.ServletParametersException;
import com.transcargo.action.ServletValidationException;
import com.transcargo.db.dbException;
import com.transcargo.geo.Country;
import com.transcargo.geo.GeoObjectNotFoundException;
import com.transcargo.rpc.RPCOutput;

public class GetCountryRequest extends Request
{
	private String cid = "";
	private String xml = "";
	
    private void servletGetValues(HttpServletRequest request) throws ServletParametersException {
		cid = request.getParameter("cid");
		if (cid == null) cid = "";
    }
    private void servletValidateValues() throws ServletValidationException {
    	if (cid.length() == 0) throw new ServletValidationException("Empty cid");
    }
    
    private void servletExecuteRequest() throws ServletRequestException {
    	try {
    		Country country = new Country(Integer.parseInt(cid), true, dbase);
    		xml =  RPCOutput.generate(country);
    	} catch (GeoObjectNotFoundException e) {
    		throw new ServletRequestException();
    	}
    }
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = null;
		try {
            out = response.getWriter();
            servletGetValues(request);
            servletValidateValues();
            servletExecuteRequest();
            out.println(xml);
	    } catch (ServletParametersException e) {
           sendRedirect(response, "index.jsp");
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletRequestException e) {
            String xml =  RPCOutput.generate(false);
            out.println(xml);
        }  catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
    }    

}
